package com.jyw.system.config;

import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;
import me.chanjar.weixin.common.redis.WxRedisOps;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import me.chanjar.weixin.mp.config.impl.WxMpRedisConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;

/**
 * @author Created by ZhangCheng on 2024/01/26
 */
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WxMpConfiguration {

    private final WxMpProperties properties;

    @Resource
    public RedisTemplate redisTemplate;

    @Bean
    public WxMpService wxMpService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        final WxMpProperties.MpConfig mpConfig = this.properties.getMpConfig();
        WxMpDefaultConfigImpl configStorage;
        if (this.properties.isUseRedis()) {
            RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
            WxRedisOps redisOps = new RedisTemplateWxRedisOps(new StringRedisTemplate(factory));
            configStorage = new WxMpRedisConfigImpl(redisOps, mpConfig.getAppId());
        } else {
            configStorage = new WxMpDefaultConfigImpl();
        }

        configStorage.setAppId(mpConfig.getAppId());
        configStorage.setSecret(mpConfig.getAppSecret());
        configStorage.setToken(mpConfig.getToken());
        configStorage.setAesKey(mpConfig.getAesKey());
        wxMpService.setWxMpConfigStorage(configStorage);
        return wxMpService;
    }
}
